package com.serkol.ams;

import com.serkol.component.LocalUtil;
import com.serkol.constant.ResultCode;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

//@Configuration
//@EnableOpenApi
public class SwaggerConfig {

  @Bean
  public Docket createRestApi() {
    System.out.println("SwaggerConfig");
    // 获取api基础信息
    return new Docket(DocumentationType.OAS_30)
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.serkol.ams.controller"))
        .paths(PathSelectors.any())
        .build()
        .globalRequestParameters(globalRequestParameters())
        .globalResponses(HttpMethod.POST, getResponseParameters())
        .globalResponses(HttpMethod.GET, getResponseParameters())
        .apiInfo(apiInfo());
  }

  private List<Response> getResponseParameters() {
    List<Response> responseParameters = new ArrayList<Response>();
    for (ResultCode superviseUnitEnum : ResultCode.values()) {
      ResponseBuilder responseBuilder = new ResponseBuilder();
      responseBuilder.code(String.valueOf(superviseUnitEnum.getCode()));
      responseBuilder.description(LocalUtil.get(superviseUnitEnum.getMsg()));

      responseParameters.add(responseBuilder.build());
    }
    return responseParameters;
  }

  /**
   * 请求头配置
   *
   * @return
   */
  private List<RequestParameter> globalRequestParameters() {
    RequestParameterBuilder parameterBuilder =
        new RequestParameterBuilder()
            .in(ParameterType.HEADER)
            .name("Authorization")
            .required(false)
            .query(param -> param.model(model -> model.scalarModel(ScalarType.STRING)));

    RequestParameterBuilder parameterBuilder1 =
        new RequestParameterBuilder()
            .in(ParameterType.HEADER)
            .name("terminal")
            .required(false)
            .query(param -> param.model(model -> model.scalarModel(ScalarType.STRING)));
    return List.of(parameterBuilder1.build(), parameterBuilder.build());
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("Oauth Server API")
        .description("Oauth Server文档API")
        .version("1.0")
        .termsOfServiceUrl("http://localhost")
        .build();
  }
}